package com.xckj.ibox.presenter;

import androidx.annotation.NonNull;

import com.xckj.ibox.bean.BaseBean;
import com.xckj.ibox.bean.LoginBean;
import com.xckj.ibox.framework.net.RetrofitManager;
import com.xckj.ibox.global.Constant;
import com.xckj.ibox.iview.ILoginView;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @Author: ChenYao
 * @Describe: 登录
 * @Date: 2023/6/12 17:40
 */
public class LoginPresenter {
    private final ILoginView loginView;

    public LoginPresenter(ILoginView loginView) {
        this.loginView = loginView;
    }

    public void login(String phone, String code, String permanent) {
        loginView.showLoading();
        Call<BaseBean<LoginBean>> call = RetrofitManager.getInstance().getService().login(phone, code, permanent);
        call.enqueue(new Callback<BaseBean<LoginBean>>() {
            @Override
            public void onResponse(@NonNull Call<BaseBean<LoginBean>> call, @NonNull Response<BaseBean<LoginBean>> response) {
                if (response.isSuccessful()) {
                    BaseBean<LoginBean> baseBean = response.body();
                    if (Constant.SUCCESS_CODE == Objects.requireNonNull(baseBean).code) {
                        loginView.loginSuccess(baseBean.data);
                    } else {
                        loginView.loginFailed(baseBean.msg);
                    }
                } else {
                    loginView.loginFailed("请求失败");
                }
                loginView.hideDialog();
            }

            @Override
            public void onFailure(@NonNull Call<BaseBean<LoginBean>> call, @NonNull Throwable t) {
                t.printStackTrace();
                loginView.loginFailed("请求失败");
                loginView.hideDialog();
            }
        });
    }
}
